import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    StyleSheet,
    SafeAreaView,
    Modal,
    ScrollView,
    DeviceEventEmitter, Platform
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, getCarRegisterDate, getMileFormat, getPriceFormat, getStoreStatus, getSaleStatus, getCheckStatus, getPurchaseType } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import Loading from '../../utils/Loading';
import { ToastToUser } from '../../utils/CustomToast';
import GoodsInfoBox from './orderComponents/GoodsInfoBox';
import CarInfoBox from './orderComponents/CarInfoBox';
import BuyerInfoBox from './orderComponents/BuyerInfoBox';
import GuarantePriceBox from './orderComponents/GuarantePriceBox';
import ReceiveAccountBox from './orderComponents/ReceiveAccountBox';
import BankInfoPop from './orderComponents/BankInfoPop';
import PriceInfoPop from './orderComponents/PriceInfoPop';
import {OrderStatus} from "../../utils/Enum";
import AndroidModule from "../../utils/AndroidConnent";

const isIos = Platform.OS == 'ios';


let navigation = null
/**
 * 买家报价订单确认
 */
export default class BuyerStartOrderPage extends Component {

    constructor(props) {
        super(props);
        let carId = this.props.route && this.props.route.params && this.props.route.params.carId ? this.props.route.params.carId : '';
        let merchantId = this.props.route && this.props.route.params && this.props.route.params.merchantId ? this.props.route.params.merchantId : '';
        let quotationRecordId = this.props.route && this.props.route.params && this.props.route.params.quotationRecordId ? this.props.route.params.quotationRecordId : '';
        let buyerMerchantName = this.props.route && this.props.route.params && this.props.route.params.buyerMerchantName ? this.props.route.params.buyerMerchantName : '';
        this.state = {
            carId,
            merchantId,
            quotationRecordId,
            quotationRecordStatus: '1',//报价状态(缺省空表示未报价) 1已报价 2报价已确认 3已下单、4已作废	
            carInfo: {},
            quotationData: {},
            sendAddress: '',//发货地址
            sendName: '',//发货人
            sendPhone: '',//发货人电话
            receivePaymentAccountName: '',//收款账户名称
            receivePaymentBank: '',//收款银行
            receivePaymentBankAccount: '',//收款银行账号
            receivePaymentBankId: '',//银行账号id

            buyerMerchantName: buyerMerchantName,
            merchantAbbreviation: '',//卖家商户名称
            isShowBankInfo: false,
            areaInfo: null,
            merchantInfo: {},
            isShowPriceInfo: false,
            prePayRate: '',//预付款比例

            showAlertCommonView: false,
            buyerMerchantId: null,
            buyerUserId: null,
            sellerMerchantId: null,

            isAgree: true,

        };
    }

    componentDidMount() {

        // this.uploadSuccessListener = DeviceEventEmitter.addListener('webViewConfirm', e => {
        //     console.log('webViewConfirm==', e);
        //     if(e.isConfirm == 1){
        //         this.setState({
        //             isAgree: true
        //         })
        //     }
        // })

        this.getCarDetails()

        if (this.state.quotationRecordId != '') {
            this.getByquotationRecordId()
        } else {
            this.getQuotationByCarId()
        }

        this.getOwnCompanyInfo()

        this.nowLoginUserDetail()
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                {/* 顶部导航栏 */}
                <Header navigation={navigation} Title={'确认订单'} bgColor={'#ffffff'} ></Header>

                <ScrollView style={{ flex: 1, paddingHorizontal: 8 }} showsVerticalScrollIndicator={false}>

                    {/* 发货信息 */}
                    <GoodsInfoBox
                        title={'收货信息'}
                        navigation={this.props.navigation}
                        sendAddress={this.state.sendAddress}
                        sendName={this.state.sendName}
                        sendPhone={this.state.sendPhone}
                        merchantInfo={this.state.merchantInfo}
                        onConfirm={(result, name, phone, areaInfo) => {
                            console.log('areaInfo', areaInfo)
                            this.setState({
                                sendAddress: result,
                                sendName: name,
                                sendPhone: phone,
                                areaInfo: areaInfo
                            })
                        }}
                    />

                    <View style={styles.orderInfoContain}>
                        <Text style={styles.titleText}>{this.state.merchantAbbreviation}</Text>
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Image style={styles.carImg} source={{ uri: getImgUrl(this.state.carInfo.mainPic) }} />
                            <View style={styles.carInfoBox}>
                                <Text style={styles.brandText}>{this.state.carInfo.seriesName + ' ' + this.state.carInfo.speciesName}</Text>
                                <Text style={styles.carInfoText}>{this.getSubCarInfo(this.state.carInfo)}</Text>
                                <Text style={styles.carPriceText}>{'收购价 ' + this.state.quotationData.quotationPrice / (10000 * 100) + '万元'}</Text>
                            </View>
                        </View>

                        <View style={styles.itemPriceContain}>
                            <Text style={styles.itemPriceTitle}>预付比例</Text>
                            <Text style={styles.itemPriceValue}>{'全款'}</Text>
                        </View>
                        <View style={styles.itemPriceContain}>
                            <Text style={styles.itemPriceTitle}>预付车款</Text>
                            <Text style={styles.itemPriceValue}>{'¥' + (this.state.quotationData.advancePayment + this.state.quotationData.tailPayment) / (100)}</Text>
                        </View>

                        <View style={styles.itemPriceContain}>
                            <Text style={styles.itemPriceTitle}>预结算尾款</Text>
                            <Text style={styles.itemPriceValue}>{'¥0.00'}</Text>
                        </View>

                        <View style={styles.itemPriceContain}>
                            <Text style={styles.itemPriceTitle}>门店服务费</Text>
                            <Text style={styles.itemPriceValue}>{'¥' + this.state.quotationData.detectionFee / (100)}</Text>
                        </View>

                        <View style={styles.itemPriceContain}>
                            <Text style={styles.itemPriceTitle}>运费</Text>
                            <Text style={styles.itemPriceValue}>到付</Text>
                        </View>

                        <TouchableOpacity style={styles.itemPriceContain}
                            onPress={() => { this.setState({ isShowPriceInfo: true }) }}>
                            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                <Text style={styles.itemPriceTitle}>总计</Text>
                                <Image style={styles.questionImg} source={require('source/image/question_icon.png')} />
                            </View>

                            <Text style={[styles.itemPriceValue, { color: '#ED542E' }]}>{'¥' + this.state.quotationData.tradePrice / (100)}</Text>
                        </TouchableOpacity>

                    </View>


                    <View style={styles.orderInfoContain}>
                        <View style={styles.infoBox}>
                            <Text style={styles.itemTitleText}>保证金</Text>
                            <Text style={styles.itemTitleText}>{'从保证金账户冻结，交易完成后解冻'}</Text>
                        </View>
                        <View style={styles.infoBox}>
                            <Text style={styles.itemTitleText}>信用担保</Text>
                            <Text style={styles.itemPriceText}>{'¥' + this.state.quotationData.contractDeposit / 100}</Text>
                        </View>

                    </View>

                    {/* 收款账户 */}
                    {/* <ReceiveAccountBox
                        isShowModify={false}
                        receivePaymentBank={this.state.receivePaymentBank}
                        receivePaymentBankAccount={this.state.receivePaymentBankAccount}
                        receivePaymentAccountName={this.state.receivePaymentAccountName}
                        receivePaymentBankId={this.state.receivePaymentBankId}
                        navigation={this.props.navigation}
                        completion={(result) => {
                            console.log(result)
                            this.setState({
                                receivePaymentBank: result.accountBank,
                                receivePaymentBankAccount: result.accountNo,
                                receivePaymentAccountName: result.accountName,
                                receivePaymentBankId: result.id
                            })
                        }}
                    /> */}

                    {/* 全款预付须知 */}
                    <View style={styles.agreeBg}>
                        <TouchableOpacity
                            style={styles.checkBox}
                            activeOpacity={0.8}
                            onPress={() => {
                                let isAgree = this.state.isAgree
                                this.setState({
                                    isAgree: !isAgree
                                })
                            }}
                        >
                            {
                                isIos ? <Image style={styles.checkIcon} source={{ uri: this.state.isAgree ? 'agent_check' : 'agent_uncheck' }} />
                                :
                                <Image style={styles.checkIcon} source={{ uri: this.state.isAgree ? 'icon_selector_checked_2' : 'icon_selector_unchecked_2' }}></Image>
                            }

                            <Text style={styles.agreeText}>本人已阅读 </Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            activeOpacity={0.8}
                            onPress={() => {
                                navigation.navigate('WebView', { source: 'https://m.shuaiche.com/static/protocol/allMoneyPrePayAgreement.html', title: '风险确认函' })
                            }}
                        >
                            <Text style={styles.agreementText}>《风险确认函》</Text>
                        </TouchableOpacity>
                        <Text style={styles.agreeText}> ，愿意承担交易风险 </Text>
                    </View>


                    <TouchableOpacity
                        style={styles.lookBankInfoContain}
                        onPress={() => {
                            // this.setState({
                            //     isShowBankInfo:true
                            // })
                        }}>
                        {/* <Text style={styles.lookBtnText}>{'查看收款账户 >'}</Text> */}
                    </TouchableOpacity>

                </ScrollView>

                {/* 底部按钮 */}
                {this.renderBottomBtn()}

                {this.state.isShowBankInfo ?
                    <BankInfoPop
                        navigation={navigation}
                        visible={this.state.isShowBankInfo}
                        onClose={() => {
                            this.setState({
                                isShowBankInfo: false
                            })
                        }}
                        receivePaymentBank={this.state.receivePaymentBank}
                        receivePaymentBankAccount={this.state.receivePaymentBankAccount}
                        receivePaymentAccountName={this.state.receivePaymentAccountName}

                    />
                    :
                    null
                }

                {this.state.isShowPriceInfo ?
                    <PriceInfoPop
                        navigation={navigation}
                        visible={this.state.isShowPriceInfo}
                        onClose={() => {
                            this.setState({
                                isShowPriceInfo: false
                            })
                        }}
                        receivePaymentBank={this.state.receivePaymentBank}
                        receivePaymentBankAccount={this.state.receivePaymentBankAccount}
                        receivePaymentAccountName={this.state.receivePaymentAccountName}

                    />
                    :
                    null
                }

                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        );
    }

    renderBottomBtn() {
        return (
            <View style={[styles.bottomBox, { height: 50 + Constant.bottomHeight }]}>
                <View style={styles.bottomBox1}>

                    <TouchableOpacity
                        style={styles.bottomitemBox}
                        activeOpacity={0.8}
                        onPress={() => {
                            this.consultOnline()
                        }}
                    >
                        <Image style={styles.bottomitemImg} source={require('source/image/chat_online_icon.png')} />
                        <Text style={styles.bottomitemText}>在线咨询</Text>
                    </TouchableOpacity>

                    {/*<TouchableOpacity*/}
                    {/*    activeOpacity={0.8}*/}
                    {/*    style={styles.bottomLeftItemBox}*/}
                    {/*    onPress={() => {*/}
                    {/*        this.quotationReject()*/}
                    {/*    }}*/}
                    {/*>*/}
                    {/*    <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}*/}
                    {/*        colors={['#F5F5F5', '#F5F5F5']}*/}
                    {/*        style={styles.itemInnerBox}*/}
                    {/*    >*/}
                    {/*        <Text style={styles.bottomRightItemText1}>取消订单</Text>*/}
                    {/*    </LinearGradient>*/}
                    {/*</TouchableOpacity>*/}
                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={styles.bottomRightItemBox1}
                        onPress={() => {
                            this.confirmOfferPrice()
                        }}
                    >
                        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                            colors={['#FFEF3A', '#FFDB1B']}
                            style={styles.itemInnerBox}>
                            <Text style={styles.bottomRightItemText}>确认下单</Text>

                        </LinearGradient>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    consultOnline() {
        let param = {
            carId: this.state.carId,
            buyerMerchantId: this.state.buyerMerchantId,
            sellerMerchantId: this.state.sellerMerchantId,
            buyerUserId: this.state.buyerUserId,
        }

        if (this.Loading) {
            this.Loading.show();
        }

        HttpUtils.postRequest(HttpUrls.quotationConsult, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {

                    setTimeout(() => {
                        navigation.navigate('MessageChat', {
                            imGroupId: result.data.imGroupId,
                            carId: this.state.carId,
                        })
                    }, 500);

                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getSubCarInfo(item) {

        let carInfoStr = ''
        if (item.registerDate && item.registerDate != null) {
            carInfoStr = getCarRegisterDate(item.registerDate)
        }

        if (item.mileage && item.mileage != 0) {
            carInfoStr = carInfoStr + ' | ' + getMileFormat(item.mileage)
        }

        if (item.cityName && item.cityName != '') {
            if (carInfoStr != '') {
                carInfoStr = carInfoStr + ' | ' + item.cityName
            } else {
                carInfoStr = item.cityName
            }

        }

        return carInfoStr
    }

    setShowConfirmModal(isShow) {
        this.setState({
            showConfirmModal: isShow
        })
    }

    nowLoginUserDetail() {
        HttpUtils.getRequest(HttpUrls.nowLoginUserDetail)
            .then((result) => {

                if (result.code == 0) {
                    this.setState({
                        sendPhone: result.data?.phone || '',
                        sendName: result.data?.fullname || ''
                    })
                }
            })
            .catch((error) => {
            });
    }

    getCarDetails() {
        let param = {
            carId: this.state.carId,
            merchantId: this.state.merchantId
        }
        if (this.Loading) {
            this.Loading.show();
        }

        HttpUtils.getRequest(HttpUrls.getOthersCarDetails, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data
                this.setState({
                    carInfo: data,
                    merchantAbbreviation: data.merchantAbbreviation
                })
                l
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getOwnCompanyInfo() {

        let param = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.getMerchantDetail, param)
            .then((result) => {

                if (result.code == 0) {
                    let data = result.data
                    this.setState({
                        sendAddress: data.address,
                        // sendPhone: data.phone,
                        // sendName: data.owner,
                        merchantInfo: data
                    })
                }
            })
            .catch((error) => {

            });
    }

    getQuotationByCarId() {
        let param = {
            carId: this.state.carId
        }
        HttpUtils.getRequest(HttpUrls.getQuotationByCarId, param)
            .then((result) => {
                if (result.data) {
                    this.setState({
                        quotationData: result.data,
                        quotationRecordId: result.data.quotationRecordId,
                        receivePaymentBank: result.data.sellerReceiveBankName,
                        receivePaymentBankAccount: result.data.sellerReceiveBankAccount,
                        receivePaymentAccountName: result.data.sellerReceiveAccountName,
                        prePayRate:Math.round(result.data.advancePayment/result.data.quotationPrice*100),
                        buyerMerchantId: result.data.buyerMerchantId,
                        buyerUserId: result.data.buyerUserId,
                        sellerMerchantId: result.data.sellerMerchantId
                    })
                }
            })
            .catch((error) => {

            });
    }

    getByquotationRecordId() {
        let param = {

            quotationRecordId: this.state.quotationRecordId
        }

        HttpUtils.getRequest(HttpUrls.getByquotationRecordId, param)
            .then((result) => {
                if (result.data) {
                    this.setState({
                        quotationData: result.data,
                        receivePaymentBank: result.data.sellerReceiveBankName,
                        receivePaymentBankAccount: result.data.sellerReceiveBankAccount,
                        receivePaymentAccountName: result.data.sellerReceiveAccountName,
                        prePayRate:Math.round(result.data.advancePayment/result.data.quotationPrice*100)
                    })
                }

            })
            .catch((error) => {

            });
    }


    confirmOfferPrice() {
        let param = {

            quotationRecordId: this.state.quotationRecordId,

            buyerConsigneeName: this.state.sendName,
            buyerConsigneePhone: this.state.sendPhone,
            buyerConsigneeAdress: this.state.sendAddress,

            buyerConsigneeProvince: this.state.areaInfo == null ? this.state.merchantInfo.province : this.state.areaInfo.province,
            buyerConsigneeCity: this.state.areaInfo == null ? this.state.merchantInfo.city : this.state.areaInfo.city,
            buyerConsigneeDistrict: this.state.areaInfo == null ? this.state.merchantInfo.district : this.state.areaInfo.area,

            buyerConsigneeProvinceName: this.state.areaInfo == null ? this.state.merchantInfo.provinceName : this.state.areaInfo.provinceName,
            buyerConsigneeCityName: this.state.areaInfo == null ? this.state.merchantInfo.cityName : this.state.areaInfo.cityName,
            buyerConsigneeDistrictName: this.state.areaInfo == null ? this.state.merchantInfo.districtName : this.state.areaInfo.areaName,

            // 全款预付 下单参数标识   quotationOrderPayType->1 新增的
            quotationOrderPayType: 1
        }

        if(!this.state.isAgree){
            ToastToUser('请阅读并确认风险提示')
            return
        }

        this.Loading.show('订单确认中...')
        HttpUtils.postRequest(HttpUrls.addQuotationOrder, param)
            .then((result) => {
                this.Loading.hide()
                if (result.code == 0) {
                    ToastToUser('确认报价成功')
                    DeviceEventEmitter.emit('offerPriceStateChanged', {});
                    DeviceEventEmitter.emit('commonEvent', { type: 'offerPriceConfrimSuccess' })

                    navigation.replace('NormalOrderDetail', { orderNo: result.data.orderNo })
                    // setTimeout(() => {
                    //     navigation.goBack()
                    // }, 1500);

                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }

            })
            .catch((error) => {
                this.Loading.hide()
            });
    }

    quotationReject() {
        let params = {
            quotationRecordId: this.state.quotationRecordId,
            operator: Constant.userInfo.fullname
        }
        this.Loading.show('订单取消中...')
        HttpUtils.postRequest(HttpUrls.quotationCancel, params).then(result => {
            this.Loading.hide()
            if (result.code == 0) {
                ToastToUser('取消成功')
                DeviceEventEmitter.emit('offerPriceStateChanged', {});
                setTimeout(() => {
                    navigation.goBack()
                }, 1500);
            } else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        }).catch(err => {
            this.Loading.hide()
        })
    }



};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    desText: {
        marginVertical: 10,
        color: '#ED542E',
        fontSize: 14,
        lineHeight: 20,
    },
    bottomBox: {
        width: '100%',
        flexDirection: 'row',
        alignItems: 'flex-start',
        justifyContent: 'flex-end',
        backgroundColor: '#fff',
        paddingHorizontal: 16,
        borderTopColor: '#e4e4e4',
        borderTopWidth: 0.5
    },
    bottomBox1: {
        width: '100%',
        height: 50,
        flexDirection: 'row',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
    },
    bottomLeftItemBox: {
        marginTop: 12,
        flex: 1.2,
        height: 36,
    },

    bottomRightItemBox: {
        marginTop: 12,
        width: 140,
        height: 36,
    },
    bottomRightItemBox1: {
        marginLeft: 15,
        marginTop: 12,
        flex: 1.8,
        height: 36,
    },
    itemInnerBox: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 18,

    },
    bottomRightItemText: {
        color: '#222',
        fontSize: 14,
    },
    bottomRightItemText1: {
        color: '#222',
        fontSize: 14,
    },

    orderInfoContain: {
        marginTop: 10,
        width: '100%',

        backgroundColor: '#fff',
        borderRadius: 6,
        paddingHorizontal: 16,
        paddingVertical: 12
    },
    carImg: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f5f5f5'
    },
    carInfoBox: {
        flex: 1,
        flexDirection: 'column',
        alignItems: 'flex-start',
        justifyContent: 'center',
        marginLeft: 12
    },
    brandText: {
        lineHeight: 20,
        color: '#333333',
        fontSize: 14,
        fontWeight: '500'
    },
    carInfoText: {
        marginTop: 4,
        fontSize: 12,
        color: '#333'
    },
    carPriceText: {
        marginTop: 8,
        fontSize: 14,
        color: '#333333'
    },

    itemPriceContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 46
    },
    itemPriceTitle: {
        fontSize: 14,
        color: '#333333'
    },
    itemPriceValue: {
        fontSize: 14,
        color: '#333333',
        fontWeight: 'bold'
    },
    titleText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
        marginBottom: 10
    },
    infoBox: {
        height: 46,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    itemTitleText: {
        color: '#333',
        fontSize: 14,
    },
    itemPriceText: {
        fontSize: 14,
        fontWeight: '500',
        color: '#333'
    },
    lookBankInfoContain: {
        height: 50,
        justifyContent: 'center',
        alignItems: 'center'
    },
    lookBtnText: {
        fontSize: 14,
        color: '#FF7B00'
    },
    questionImg: {
        marginLeft: 3,
        width: 13,
        height: 13,
    },


    // 右侧按钮样式
    rightBox: {
        height: '100%',
        width: 70,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    rightText: {
        fontSize: 14,
        color: '#333333',

    },

    // 在线咨询
    bottomitemBox: {
        height: '100%',
        width: 45,
        marginRight: 5,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    bottomitemImg: {
        width: 18,
        height: 18
    },
    bottomitemText: {
        color: '#333333',
        fontSize: 10,
        marginTop: 4,
    },

    // 协议单选按钮样式
    agreeBg: {
        marginTop: 10,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    checkBox: {
        height: 30,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    checkIcon: {
        marginRight: 8,
        width: 18,
        height: 18,
    },
    agreementText: {
        color: '#ED542E',
        fontSize: 14
    },

});
